package com.xsherl.leetcode.solution;

/**
 * @Author: sherl
 * @Date: 2021/5/24 21:01
 */
public class SpiralMatrix2 {

    private int[][] direction = new int[][]{
            {1, 0},
            {0, 1},
            {-1, 0},
            {0, -1}
    };

    /**
     * 思路同 {@link SpiralMatrix}
     */
    public int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        int i = 0;
        int j = 0;
        int dx = 1;
        int dy = 0;
        int t = 1;
        int d = 0;
        while (t <= n * n) {
            res[j][i] = t++;
            i += dx;
            j += dy;
            if (i < 0 || j < 0 || i == n || j == n || res[j][i] > 0) {
                i -= dx;
                j -= dy;
                d++;
                if (d > 3) {
                    d = 0;
                }
                dx = direction[d][0];
                dy = direction[d][1];
                i += dx;
                j += dy;
            }
        }
        return res;
    }

}
